<template>
	<view class="login-container">
		<image class="login-bg" src="/static/背景.jpg" mode="aspectFill"></image>
		<view class="login-box">
			<view class="login-title">智慧校园</view>
			<view class="login-subtitle">保安管理系统</view>
			
			<!-- 手机号输入 -->
			<view class="input-group">
				<image src="/static/手机号.png" mode="aspectFit" class="input-icon"></image>
				<input type="number" placeholder="请输入手机号" maxlength="11" v-model="phone" placeholder-class="input-placeholder" />
			</view>
			
			<!-- 验证码输入 -->
			<view class="input-group">
				<image src="/static/验证码.png" mode="aspectFit" class="input-icon"></image>
				<input type="number" placeholder="请输入验证码" maxlength="6" v-model="code" placeholder-class="input-placeholder" />
				<view class="code-btn" @click="getCode">{{codeText}}</view>
			</view>
			
			<!-- 登录按钮 -->
			<view class="login-btn" @click="handleLogin">
				<text>登录系统</text>
			</view>
			
			<!-- 其他登录方式 -->
			<view class="other-login">
				<view class="line"></view>
				<text>微信一键登录</text>
				<view class="line"></view>
			</view>
			
			<!-- 微信登录 -->
			<view class="wx-login-box">
				<view class="wx-login-icon" @click="wxLogin">
					<image src="/static/微信.png" mode="aspectFit"></image>
				</view>
			</view>
		</view>
		
		<view class="system-info">
			<text>校园保安管理系统 v1.0</text>
		</view>
		
		<!-- 微信授权弹窗 -->
		<view class="auth-modal" v-if="showAuthModal">
			<view class="auth-mask" @click="cancelAuth"></view>
			<view class="auth-content">
				<view class="auth-header">
					<image class="wx-icon" src="/static/微信.png" mode="aspectFit"></image>
					<text>使用微信快捷登录</text>
				</view>
				
				<view class="auth-body">
					<text class="auth-title">智慧校园 申请使用</text>
					<view class="auth-info">
						<text>你的头像、昵称</text>
					</view>
					
					<view class="auth-user-info">
						<view class="user-avatar-box">
							<image class="user-avatar" :src="tempUserInfo.avatarUrl || '/static/logo.png'" mode="aspectFill"></image>
						</view>
						<text class="user-nickname">{{tempUserInfo.nickName || '微信用户'}}</text>
					</view>
				</view>
				
				<view class="auth-footer">
					<view class="auth-btn cancel" @click="cancelAuth">拒绝</view>
					<view class="auth-btn confirm" @click="confirmAuth">允许</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				phone: '',
				code: '',
				codeText: '获取验证码',
				timer: null,
				countdown: 60,
				userInfo: null,
				hasUserInfo: false,
				showAuthModal: false,
				tempUserInfo: {
					nickName: '',
					avatarUrl: ''
				},
				wxLoginCode: '' // 存储微信登录code
			}
		},
		methods: {
			// 获取验证码
			getCode() {
				if (this.timer) return;
				if (!this.phone || this.phone.length !== 11) {
					uni.showToast({
						title: '请输入正确的手机号',
						icon: 'none'
					});
					return;
				}
				
				// 显示加载中
				uni.showLoading({
					title: '发送中...'
				});
				
				// 发送验证码请求到后端
				uni.request({
					url: 'http://172.20.10.3:9527/security/security/sms/send',  // 替换为您的验证码发送接口
					method: 'POST',
					data: {
						phone: this.phone
					},
					header: {
						'content-type': 'application/json'
					},
					success: (res) => {
						console.log('发送验证码响应', res);
						
						if (res.data && res.data.code === 200) {
							// 发送成功
							uni.showToast({
								title: '验证码已发送',
								icon: 'success'
							});
							
							// 开始倒计时
							this.startCountdown();
						} else {
							// 发送失败
							uni.showToast({
								title: res.data?.message || '验证码发送失败',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						console.error('验证码发送请求失败', err);
						uni.showToast({
							title: '网络请求失败，请重试',
							icon: 'none'
						});
					},
					complete: () => {
						uni.hideLoading();
					}
				});
			},
			
			// 开始倒计时
			startCountdown() {
				this.countdown = 60;
				this.codeText = `${this.countdown}s`;
				this.timer = setInterval(() => {
					this.countdown--;
					this.codeText = `${this.countdown}s`;
					if (this.countdown <= 0) {
						clearInterval(this.timer);
						this.timer = null;
						this.codeText = '获取验证码';
					}
				}, 1000);
			},
			
			// 登录方法
			handleLogin() {
				if (!this.phone || this.phone.length !== 11) {
					uni.showToast({
						title: '请输入正确的手机号',
						icon: 'none'
					});
					return;
				}
				
				if (!this.code || this.code.length !== 6) {
					uni.showToast({
						title: '请输入正确的验证码',
						icon: 'none'
					});
					return;
				}
				
				// 显示加载中
				uni.showLoading({
					title: '登录中...'
				});
				
				// 调用后端登录接口
				uni.request({
					url: 'http://172.20.10.3:9527/security/security/phone/login',  // 替换为您的手机登录接口
					method: 'POST',
					data: {
						phone: this.phone,
						code: this.code
					},
					header: {
						'content-type': 'application/json'
					},
					success: (res) => {
						console.log('手机登录响应', res);
						
						if (res.data && res.data.code === 200) {
							// 登录成功
							// 构建用户信息，优先使用后端返回的信息，如果没有则使用默认值
							// 生成随机用户名，格式为保安员+手机号后4位
							const randomName = '保安员' + this.phone.substring(this.phone.length - 4);
							
							// 默认用户信息
							const defaultUserInfo = {
								nickName: randomName,
								avatarUrl: '/static/logo.png',
								phone: this.phone
							};
							
							// 合并后端返回的信息和默认信息
							let userInfo = defaultUserInfo;
							if (res.data.data && res.data.data.userInfo) {
								userInfo = {
									...defaultUserInfo,
									...res.data.data.userInfo
								};
							}
							
							// 确保基本信息存在
							if (!userInfo.nickName) {
								userInfo.nickName = randomName;
							}
							if (!userInfo.avatarUrl) {
								userInfo.avatarUrl = '/static/logo.png';
							}
							if (!userInfo.phone) {
								userInfo.phone = this.phone;
							}
							
							console.log('保存的用户信息:', userInfo);
							
							// 保存用户信息和token
							uni.setStorageSync('userInfo', userInfo);
							uni.setStorageSync('token', (res.data.data && res.data.data.token) || 'phone-token-' + Date.now());
							
							// 登录成功提示
							uni.showToast({
								title: '登录成功',
								icon: 'success',
								duration: 1500
							});
							
							// 登录成功跳转到首页
							setTimeout(() => {
								uni.reLaunch({
									url: '/pages/index/index'
								});
							}, 1500);
						} else {
							// 登录失败
							uni.showToast({
								title: res.data?.message || '验证码错误或已过期',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						console.error('登录请求失败', err);
						uni.showToast({
							title: '网络请求失败，请重试',
							icon: 'none'
						});
					},
					complete: () => {
						uni.hideLoading();
					}
				});
			},
			
			// 微信登录 - 第一步：获取登录凭证
			wxLogin() {
				// #ifdef MP-WEIXIN
				// 先获取微信登录凭证code
				uni.login({
					provider: 'weixin',
					success: (loginRes) => {
						console.log('获取登录凭证成功', loginRes);
						this.wxLoginCode = loginRes.code;
						
						// 获取微信用户信息并显示在授权弹窗
						// 由于小程序新版本限制，我们需要使用 wx.getUserInfo 获取基本信息
						// 这个API不需要用户主动授权，可以先获取到默认头像
						wx.getUserInfo({
							success: (userInfoRes) => {
								console.log('获取到基本用户信息', userInfoRes);
								this.tempUserInfo = {
									nickName: userInfoRes.userInfo.nickName || '微信用户',
									avatarUrl: userInfoRes.userInfo.avatarUrl || '/static/logo.png'
								};
								
								// 显示授权弹窗
								this.showAuthModal = true;
							},
							fail: (err) => {
								console.log('获取基本用户信息失败', err);
								// 失败时使用默认信息
								this.tempUserInfo = {
									nickName: '微信用户',
									avatarUrl: '/static/logo.png'
								};
								
								// 仍然显示授权弹窗
								this.showAuthModal = true;
							}
						});
					},
					fail: (err) => {
						console.error('获取登录凭证失败', err);
						uni.showToast({
							title: '登录失败，请重试',
							icon: 'none'
						});
					}
				});
				// #endif
				
				// #ifndef MP-WEIXIN
				uni.showToast({
					title: '请在微信小程序中使用此功能',
					icon: 'none'
				});
				// #endif
			},
			
			// 取消授权
			cancelAuth() {
				this.showAuthModal = false;
				this.wxLoginCode = '';
				this.tempUserInfo = {
					nickName: '',
					avatarUrl: ''
				};
			},
			
			// 确认授权 - 第二步：获取用户信息
			confirmAuth() {
				// 隐藏授权弹窗
				this.showAuthModal = false;
				
				// #ifdef MP-WEIXIN
				// 显示加载中
				uni.showLoading({
					title: '登录中...'
				});
				
				// 获取用户信息 - 必须由用户点击触发
				uni.getUserProfile({
					desc: '用于登录校园保安系统', // 声明获取用户个人信息后的用途
					lang: 'zh_CN',
					success: (profileRes) => {
						console.log('获取用户信息成功', profileRes.userInfo);
						this.userInfo = profileRes.userInfo;
						this.hasUserInfo = true;
						
						// 使用之前获取的code和用户信息进行登录
						if (this.wxLoginCode) {
							this.wxLoginWithBackend(this.wxLoginCode, profileRes.userInfo);
						} else {
							uni.hideLoading();
							uni.showToast({
								title: '登录凭证失效，请重试',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						uni.hideLoading();
						console.error('获取用户信息失败', err);
						uni.showToast({
							title: '获取信息失败，请重试',
							icon: 'none'
						});
					}
				});
				// #endif
			},
			
			// 与后端交互，处理微信登录
			wxLoginWithBackend(code, userInfo) {
				// 构建请求参数
				const params = {
					code: code,
					nickName: userInfo.nickName,
					avatarUrl: userInfo.avatarUrl,
					gender: userInfo.gender,
					city: userInfo.city,
					province: userInfo.province,
					country: userInfo.country
				};
				
				// 发送请求到后端
				uni.request({
					url: 'http://172.20.10.3:9527/security/wechat/login',
					method: 'POST',
					data: params,
					header: {
						'content-type': 'application/json'
					},
					success: (res) => {
						// 判断登录是否成功
						if (res.data && res.data.code === 200) {
							// 保存完整的用户信息到本地存储
							const savedUserInfo = {
								...userInfo
							};
							
							// 如果后端返回了用户信息，则合并
							if (res.data.data && res.data.data.userInfo) {
								Object.assign(savedUserInfo, res.data.data.userInfo);
							}
							
							// 确保基本信息存在
							if (!savedUserInfo.nickName) {
								savedUserInfo.nickName = userInfo.nickName || '微信用户';
							}
							if (!savedUserInfo.avatarUrl) {
								savedUserInfo.avatarUrl = userInfo.avatarUrl || '/static/logo.png';
							}
							
							console.log('保存的微信用户信息:', savedUserInfo);
							
							uni.setStorageSync('userInfo', savedUserInfo);
							uni.setStorageSync('token', (res.data.data && res.data.data.token) || 'wx-token-' + Date.now());
							
							// 提示登录成功
							uni.showToast({
								title: '登录成功',
								icon: 'success',
								duration: 1500
							});
							
							// 登录成功跳转到首页
							setTimeout(() => {
								uni.reLaunch({
									url: '/pages/index/index'
								});
							}, 1500);
						} else {
							uni.showToast({
								title: res.data?.message || '登录失败',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						console.error('请求失败', err);
						uni.showToast({
							title: '网络请求失败，请重试',
							icon: 'none'
						});
					},
					complete: () => {
						uni.hideLoading();
					}
				});
			}
		}
	}
</script>

<style lang="scss">
	.login-container {
		position: relative;
		width: 100%;
		height: 100vh;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		
		.login-bg {
			position: absolute;
			width: 100%;
			height: 100%;
			z-index: -1;
			filter: brightness(0.9) contrast(1.1);
		}
		
		.login-box {
			width: 85%;
			background-color: rgba(32, 45, 70, 0.8);
			border-radius: 24rpx;
			padding: 50rpx 40rpx;
			box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.3);
			backdrop-filter: blur(10px);
			border: 1px solid rgba(255, 255, 255, 0.1);
			
			.login-title {
				font-size: 48rpx;
				font-weight: bold;
				text-align: center;
				margin-bottom: 20rpx;
				color: #ffffff;
				letter-spacing: 4rpx;
				text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
			}
			
			.login-subtitle {
				font-size: 30rpx;
				text-align: center;
				color: #e0e0e0;
				margin-bottom: 60rpx;
				letter-spacing: 2rpx;
			}
			
			.input-group {
				display: flex;
				align-items: center;
				height: 100rpx;
				border-bottom: 1px solid rgba(255, 255, 255, 0.2);
				margin-bottom: 30rpx;
				padding: 0 20rpx;
				
				.input-icon {
					width: 44rpx;
					height: 44rpx;
					margin-right: 20rpx;
				}
				
				input {
					flex: 1;
					height: 100%;
					font-size: 32rpx;
					color: #ffffff;
				}
				
				.input-placeholder {
					color: rgba(255, 255, 255, 0.6);
				}
				
				.code-btn {
					padding: 12rpx 24rpx;
					border-radius: 40rpx;
					background-color: #3a4e70;
					color: #FFFFFF;
					font-size: 26rpx;
					box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.3);
					border: 1px solid rgba(255, 255, 255, 0.1);
				}
			}
			
			.login-btn {
				height: 96rpx;
				background: linear-gradient(to right, #1a4380, #2b6ac4);
				border-radius: 48rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				color: #FFFFFF;
				font-size: 34rpx;
				font-weight: bold;
				margin-top: 70rpx;
				margin-bottom: 20rpx;
				box-shadow: 0 8rpx 16rpx rgba(0, 0, 0, 0.3);
				position: relative;
				overflow: hidden;
				border: 1px solid rgba(255, 255, 255, 0.1);
				
				&::after {
					content: '';
					position: absolute;
					top: 0;
					left: 0;
					right: 0;
					bottom: 0;
					background: linear-gradient(rgba(255, 255, 255, 0.1), transparent);
				}
				
				text {
					z-index: 1;
					letter-spacing: 4rpx;
				}
			}
			
			.other-login {
				display: flex;
				align-items: center;
				justify-content: center;
				margin-top: 70rpx;
				margin-bottom: 40rpx;
				
				.line {
					width: 100rpx;
					height: 1px;
					background-color: rgba(255, 255, 255, 0.2);
				}
				
				text {
					color: rgba(255, 255, 255, 0.7);
					font-size: 26rpx;
					margin: 0 20rpx;
				}
			}
			
			.wx-login-box {
				display: flex;
				justify-content: center;
				
				.wx-login-icon {
					width: 90rpx;
					height: 90rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					background-color: rgba(255, 255, 255, 0.1);
					border-radius: 50%;
					padding: 15rpx;
					box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.2);
					border: 1px solid rgba(255, 255, 255, 0.1);
					
					image {
						width: 60rpx;
						height: 60rpx;
					}
				}
			}
		}
		
		.system-info {
			position: absolute;
			bottom: 30rpx;
			font-size: 24rpx;
			color: rgba(255, 255, 255, 0.6);
			text-align: center;
		}
		
		// 微信授权弹窗样式
		.auth-modal {
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			z-index: 999;
			display: flex;
			align-items: center;
			justify-content: center;
			
			.auth-mask {
				position: absolute;
				top: 0;
				left: 0;
				right: 0;
				bottom: 0;
				background-color: rgba(0, 0, 0, 0.6);
			}
			
			.auth-content {
				width: 80%;
				background-color: #ffffff;
				border-radius: 12rpx;
				overflow: hidden;
				position: relative;
				z-index: 1000;
				box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.1);
			}
			
			.auth-header {
				padding: 30rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				border-bottom: 1px solid #f5f5f5;
				
				.wx-icon {
					width: 40rpx;
					height: 40rpx;
					margin-right: 10rpx;
				}
				
				text {
					font-size: 28rpx;
					color: #333;
				}
			}
			
			.auth-body {
				padding: 40rpx 30rpx;
				
				.auth-title {
					font-size: 32rpx;
					font-weight: bold;
					color: #333;
					margin-bottom: 30rpx;
					display: block;
					text-align: center;
				}
				
				.auth-info {
					font-size: 30rpx;
					color: #333;
					margin-bottom: 30rpx;
					text-align: center;
				}
				
				.auth-user-info {
					display: flex;
					align-items: center;
					padding: 30rpx;
					background-color: #f8f8f8;
					border-radius: 8rpx;
					
					.user-avatar-box {
						width: 80rpx;
						height: 80rpx;
						margin-right: 20rpx;
						background-color: #07c160;
						border-radius: 8rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						overflow: hidden;
					}
					
					.user-avatar {
						width: 100%;
						height: 100%;
						object-fit: cover;
					}
					
					.user-nickname {
						font-size: 28rpx;
						color: #333;
					}
				}
			}
			
			.auth-footer {
				display: flex;
				
				.auth-btn {
					flex: 1;
					height: 100rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					font-size: 32rpx;
				}
				
				.cancel {
					color: #333;
					background-color: #f2f2f2;
					border-top: 1px solid #e5e5e5;
					border-right: 1px solid #e5e5e5;
				}
				
				.confirm {
					color: #ffffff;
					background-color: #07c160;
					border-top: 1px solid #07c160;
				}
			}
		}
	}
	
	@media screen and (min-height: 700px) {
		.login-box {
			transform: translateY(-5%);
		}
	}
</style> 